package com.mobileshop.plugins;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import oracle.net.aso.s;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

import com.jfinal.ext.kit.Reflect;
import com.jfinal.plugin.IPlugin;

//本类用于解析xml描述的quartz任务
public class QuartzXmlPlugin implements IPlugin{
	
	private final  String classname="classname";
	private final  String cron="cronexp";
	private final  String enable="enable";
	private Scheduler scheduler;
	private SchedulerFactory sf;
	private String config="job.xml";
	public QuartzXmlPlugin(){}
	public QuartzXmlPlugin(String configfile){
		this.config =configfile;
	}
	public boolean start() {
		sf=new StdSchedulerFactory();
		try {
			scheduler=sf.getScheduler();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		try {
			
			List<Job> jobs=getJobs();
			for(Job job:jobs){
				if(job.enable){
					Class clazzClass=Reflect.on(job.classname).get();
					JobDetail jd =new JobDetail(job.classname, job.classname, clazzClass);
					CronTrigger trigger=new CronTrigger(job.classname, job.classname, job.cron);
					scheduler.scheduleJob(jd, trigger);
				}
			}
			scheduler.start();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		
		return true;
	}

	public boolean stop() {	
		if(scheduler!=null)
			try {
				scheduler.shutdown();
			} catch (SchedulerException e) {
				e.printStackTrace();
			}
		return 	true;
	}
	
	public List<Job> getJobs() throws DocumentException{
		List<Job> jobs=new ArrayList<Job>();
		Document doc =new SAXReader().read(this.getClass().getClassLoader().getResourceAsStream(config));
		Element root=doc.getRootElement();
		if(!root.getName().equalsIgnoreCase("jobs"))
			throw new DocumentException("PARSE ERROR:the "+config+"'s root element must be named jobs");
		List<Element> job=root.elements("job");
		for(Element e :job){
			Job j =new Job();
			j.classname=e.element(classname).getText().trim();
			j.cron=e.element(cron).getText().trim();
			j.enable=Boolean.parseBoolean(e.element(enable).getText().trim());
			jobs.add(j);
		}
		return jobs;
	}
}
class Job {
	String classname="";
	String cron="";
	boolean enable=false;
}
